<template>
  <BasicDrawer :destroyOnClose="true" v-bind="$attrs" @register="registerDrawer" showFooter title="支付" width="620px"
    @close="onClose" :maskClosable="false">
    <template #footer>
      <a-button @click="onClose">取消</a-button>
      <a-button type="primary" @click="onAffirm">确认支付</a-button>
    </template>
    <div class="card" style="width: 100%">
      <div class="c-title"> 支付明细 </div>

      <a-flex class="r-row" justify="space-between" align="center">
        <div class="r-label">充值金额</div>
        <div class="r-value">¥&nbsp;{{ myFormData.rechargePrice }}</div>
      </a-flex>

      <a-flex class="r-row" justify="space-between" align="center">
        <div class="r-label">优惠金额</div>
        <div class="r-value">¥&nbsp;{{ myFormData.saleDiscount || 0 }}</div>
      </a-flex>

      <div style="border-bottom: 1px dashed #ccc; margin: 12px 0"></div>

      <a-flex class="r-row" justify="space-between">
        <div class="r-label">应付金额</div>
        <div class="r-value2">¥&nbsp;{{ myFormData.rechargePrice - (myFormData.saleDiscount || 0) }}</div>
      </a-flex>

      <div class="c-title" style="margin-top: 32px"> 支付方式 </div>

      <a-flex class="r-row" gap="middle" align="center">
        <div class="r-label"><span class="must">*</span>支付方式</div>
        <div class="data-group">
          <div :class="['use', 'cell', myFormData.cashPayCode === o.value ? 'active' : 'tacit']" v-for="o in cashPayCodes"
            :key="o.value" @click="myFormData.cashPayCode = o.value">{{ o.label }}
          </div>
        </div>
      </a-flex>

      
      <a-flex class="r-row" gap="middle" align="center" style="position: relative">
        <div class="r-label"><span class="must">*</span>实付金额</div>
        <div>
          <div>
            <a-input-number
              v-model:value="totalFee"
              :min="0"
              :max="myFormData.rechargePrice"
              :precision="2"
              addon-after="元"
            />
          </div>
          <div class="hint" style="position: absolute" v-if="!isNil(totalFee)">
            欠款金额&nbsp;-{{ myFormData.rechargePrice - (myFormData.saleDiscount || 0) - (totalFee || 0) || 0 }}元
          </div>
        </div>
      </a-flex>
    </div>
  </BasicDrawer>
  <OrderDetail @register="registerDetail" />
</template>

<script setup>
import { defineOptions, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useMessage } from '@/hooks/web/useMessage';
import { BasicDrawer, useDrawerInner, useDrawer } from '@/components/Drawer';
import {getUserInfo} from "@/utils/auth";
import {exist} from "@/api/util.js";
import {POST} from "@/api/http.js";
import {
  shopCartRef,
  createCardUpgradeOrder,
  createShopOrder,
  getCartPayableAmount,
} from '@/views/cashier/cart.js';
import { cashPayCodes } from '@/api/ds.js';
import { round, isNil } from '@/api/util.js';
import OrderDetail from '../cashier/order-detail.vue';

const [registerDetail, { openDrawer: detailDrawer }] = useDrawer();

const router = useRouter();
const { createMessage, createConfirm } = useMessage();

defineOptions({ name: 'CashierPayment' });
const emit = defineEmits(['success']);

let masterOrderSns = ''
const totalFee = ref(0);
const myBeauticianList = ref([]);
const myFormData = ref({});
let myMemberCode = '-1';
let myCloseFtherDrawer = null;
const myRecord = ref({})
const [registerDrawer, { closeDrawer, changeLoading }] = useDrawerInner(
  async ({masterOrderSn, formData, beauticianList, memberCode, record, closeFtherDrawer }) => {
    masterOrderSns = masterOrderSn
    myBeauticianList.value = beauticianList;
    myCloseFtherDrawer = closeFtherDrawer;
    myFormData.value = formData;
    totalFee.value = myFormData.value.rechargePrice - (myFormData.value.saleDiscount || 0);
    myMemberCode = memberCode;
    myRecord.value = record;
  },
);

async function onAffirm() {
  const { cashPayCode } = myFormData.value;

  if (!cashPayCode) {
    return createMessage.error('请选择支付方式');
  }

  if (myMemberCode === '-1') {
    if (Math.abs(myFormData.value.rechargePrice - (totalFee.value || 0)) > 0.0001) {
      return createMessage.error('散客不允许欠款收银');
    }
  }

    createConfirm({
      content: '您确要支付订单吗',
      onOk: async () => {
        const data = { ...myFormData.value };
        let { rechargePrice, employeesCodeList, addTime, saleDiscount, remarks } = data;
        saleDiscount ||= 0;
        employeesCodeList = myBeauticianList.value?.filter(o => exist(o.value, employeesCodeList))?.map(o => ({
          employeeCode: o.value,
          employeeName: o.label
        })) ?? [];
        try {
          changeLoading(true);
          console.log(myRecord.value)
          const { cardNo, batchNo, cardType } = myRecord.value;
          const { employeeCode: cashierCode } = getUserInfo()?.resultBean ?? {};

          const res = await POST('/cashier/createCardRechangeOrder', {
            memberCode: myMemberCode, 
            payablePrice: myFormData.value.rechargePrice - (myFormData.value.saleDiscount || 0),
            cardType, cashierCode, cardNo, batchNo,
            referer: 'PC端', sourceCode: '20', cashPayCode: myFormData.value.cashPayCode,
            debtFee: myFormData.value.rechargePrice - (myFormData.value.saleDiscount || 0) - (totalFee.value || 0) || 0,
            rechargePrice, employeesCodeList, addTime, saleDiscount, remarks
          });

          createMessage.success('充值已完成');
          detailDrawer(true, { masterOrderSn: res.masterOrderSn });
          emit('success');
          // closeDrawer();
          console.log('closeDrawer-closeDrawer')
          myCloseFtherDrawer();
        } finally {
          changeLoading(false);
        }
      },
    });
}


function onClose() {
    closeDrawer();
}
</script>
<style lang="less" scoped>
.card {
  height: 100%;
  padding: 16px;

  .c-title {
    padding: 32px 0 6px 0;
    color: #091f3d;
    font-size: 15px;
    font-weight: 600;
  }

  .c-title:first-child {
    padding-top: 8px;
  }

  .r-row {
    margin: 12px 0;
  }

  .r-label {
    font-weight: 400;
    font-size: 16px;
    color: #666666;
  }

  .r-value {
    font-weight: 400;
    font-size: 14px;
    color: #666666;
  }

  .r-value2 {
    font-weight: 500;
    font-size: 16px;
    color: #eb6485;
  }

  .hint {
    font-weight: 400;
    font-size: 13px;
    color: #666666;
    margin-top: 4px;
  }
}
</style>

<style lang="less" scoped>
.data-group {
  display: flex;
  flex-flow: row wrap;
  align-items: center;
  cursor: pointer;
  gap: 8px 12px;

  .cell {
    padding: 4px 20px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
  }

  .tacit {
    border: 1px solid #e0e5ec;
    color: #091f3d;
  }

  .active {
    border: 1px solid @primary-color;
    background-color: @primary-color;
    color: #fff;
  }
}
</style>
